/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.photosets.Photoset;
import com.aetrion.flickr.photosets.PhotosetsInterface;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.PhotoEntry;
import com.restfb.BinaryAttachment;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.types.FacebookType;
import com.unice.miage.oobdoo.entity.Photo;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.manager.AlbumManager;
import com.unice.miage.oobdoo.manager.PhotoManager;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Jeremy Romano
 */
@WebServlet(name = "ExportServlet", urlPatterns = {"/ExportServlet"})
public class ExportServlet extends HttpServlet {

    @EJB
    private UtilisateurManager utilisateurManager;
    @EJB
    private AlbumManager albumManager;
    @EJB
    private PhotoManager photoManager;
    String FACEBOOK_API_ID = "175962519155144";
    String FACEBOOK_API_SECRET = "320d63da1c62daae63cf457bb557f936";
    String FLICKR_API_KEY = "b530efd6e5a9f25353f2e85c7d452e02";
    String FLICKR_API_SECRET = "0fbc40addb1a6f53";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>> ExportServlet");

        String source = request.getParameter("source");
        String idAlbum = request.getParameter("idAlbum");
        String forwardTo = "AlbumServlet?action=view&IdAlbum=" + idAlbum;

        request.setAttribute("origine", "export");

        if (source != null) {

            HttpSession session = request.getSession(true);
            int id = Integer.valueOf(session.getAttribute("id").toString());

            Utilisateur u = utilisateurManager.getUtilisateurById(id);

            switch (Integer.valueOf(source)) {
                case 1:
                    String tokenFB = u.getAccess_token_fb();
                    if (tokenFB != null) {
                        try {
                            int idA = Integer.valueOf(idAlbum);
                            com.unice.miage.oobdoo.entity.Album a = albumManager.getAlbumById(idA);
                            String path = this.getServletContext().getInitParameter("PATH");
                            FacebookClient facebookClient = new DefaultFacebookClient(tokenFB);
                            FacebookType aFB = facebookClient.publish("me/albums", FacebookType.class, Parameter.with("name", a.getNom()), Parameter.with("description", a.getDescription()));
                            for (Photo p : a.getPhotos()) {
                                String ressourcePATH = path + "upload/" + u.getId() + "/" + a.getId() + "/" + p.getPathFile();
                                File file = new File(ressourcePATH);
                                InputStream is = new FileInputStream(file);
                                BinaryAttachment ba = BinaryAttachment.with(p.getPathFile(), is);
                                System.out.println("ba=" + ba.getFilename());
                                facebookClient.publish(
                                        aFB.getId() + "/photos", FacebookType.class, ba, Parameter.with("message", p.getNom()));
                            }
                            forwardTo += "&message=1";
                        } catch (Exception ex) {
                            forwardTo += "&message=0";
                        } finally {
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);
                        }
                    } else {
                        System.out.println(">>>>>>>>>>>>>>>>>>>>>>> GOTO AuthServlet");
                        forwardTo = "AuthServlet";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }
                    break;

                case 2:
                    String tokenP = u.getAccess_token_picasa();
                    if (tokenP != null) {
                        try {
                            int idA = Integer.valueOf(idAlbum);
                            com.unice.miage.oobdoo.entity.Album a = albumManager.getAlbumById(idA);

                            PicasawebService ps = new PicasawebService("oobdoo");
                            ps.setAuthSubToken(tokenP, null);

                            AlbumEntry aP = new AlbumEntry();

                            aP.setTitle(new PlainTextConstruct(a.getNom()));
                            aP.setDescription(new PlainTextConstruct(a.getDescription()));

                            URL postUrl = new URL("https://picasaweb.google.com/data/feed/api/user/default");

                            AlbumEntry insertedAlbum = ps.insert(postUrl, aP);

                            URL albumPostUrl = new URL(insertedAlbum.getFeedLink().getHref());
                            String path = this.getServletContext().getInitParameter("PATH");
                            for (Photo p : a.getPhotos()) {
                                String ressourcePATH = path + "upload/" + u.getId() + "/" + a.getId() + "/" + p.getPathFile();
                                File file = new File(ressourcePATH);
                                PhotoEntry photoP = new PhotoEntry();
                                photoP.setTitle(new PlainTextConstruct(p.getNom()));
                                photoP.setDescription(new PlainTextConstruct(p.getDescription()));

                                MediaFileSource myMedia = new MediaFileSource(file, "image/jpeg");
                                photoP.setMediaSource(myMedia);

                                ps.insert(albumPostUrl, photoP);
                            }
                            forwardTo += "&message=1";
                        } catch (Exception ex) {
                            forwardTo += "&message=0";
                        } finally {
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);
                        }
                    } else {
                        System.out.println(">>>>>>>>>>>>>>>>>>>>>>> GOTO AuthServlet");
                        forwardTo = "AuthServlet";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }

                    break;
                case 3:
                    String tokenF = u.getAccess_token_flickr();
                    if (tokenF != null) {
                        Auth auth;
                        RequestContext requestContext;	// Used for making signed calls to Flickr
                        try {
                            int idA = Integer.valueOf(idAlbum);
                            com.unice.miage.oobdoo.entity.Album a = albumManager.getAlbumById(idA);

                            Flickr flickr = new Flickr(FLICKR_API_KEY, FLICKR_API_SECRET, new REST());

                            requestContext = RequestContext.getRequestContext();
                            requestContext.setSharedSecret(FLICKR_API_SECRET);

                            AuthInterface authInterface = flickr.getAuthInterface();
                            auth = authInterface.checkToken(tokenF);

                            requestContext.setAuth(auth);
                            
                            String path = this.getServletContext().getInitParameter("PATH");

                            Uploader up = flickr.getUploader();
                            
                            String ressourcePATH;
                            File file;
                            InputStream is;
                            UploadMetaData uploadMetaData;
                            int tour = 0;
                            Photoset aF = null;
                            PhotosetsInterface aFInterface = flickr.getPhotosetsInterface();
                            for (Photo p : a.getPhotos()) {
                                System.out.println(p.getNom());
                                ressourcePATH = path + "upload/" + u.getId() + "/" + a.getId() + "/" + p.getPathFile();
                                file = new File(ressourcePATH);
                                is = new FileInputStream(file);
                                uploadMetaData = new UploadMetaData(); 
                                uploadMetaData.setTitle(p.getNom());
                                uploadMetaData.setDescription(p.getDescription());
                                String photoid = up.upload(is,uploadMetaData);
                                is.close();
                                System.out.println("photoid=" + photoid);
                                if( tour == 0 )
                                {
                                    aF = flickr.getPhotosetsInterface().create(a.getNom(), a.getDescription(), photoid);
                                }
                                else
                                {
                                    aFInterface.addPhoto(aF.getId(), photoid);
                                }
                                tour++;
                            }

                            forwardTo += "&message=1";
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            forwardTo += "&message=0";
                        } finally {
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);
                        }
                    } else {
                        System.out.println(">>>>>>>>>>>>>>>>>>>>>>> GOTO AuthServlet");
                        forwardTo = "AuthServlet";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }
                    break;
            }

        } else {
            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
            dp.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
